package com.bantang.template;

import com.bantang.model.JudgeInfo;
import com.bantang.model.SandBoxParam;
import com.bantang.model.SandBoxVO;
import com.bantang.utils.CompileCodeUtil;
import com.bantang.utils.ExecResult;

import java.util.ArrayList;
import java.util.List;

/**
 * java 原生实现代码沙箱
 */
public class JavaSandBoxTemplate extends CodeSandBoxTemplate {

    @Override
    public SandBoxVO runCode(SandBoxParam sandBoxParam) {
        List<String> input = sandBoxParam.getInput();

        //运行代码
        List<String> outputValues = new ArrayList<>();
        JudgeInfo judgeInfo = new JudgeInfo();

        Long maxTime = 0L;
        for (String s : input) {

            String codeCmdRun = String.format("java -Xmx256m -cp %s Solve %s", userCodePath, s);
            ExecResult runResult = CompileCodeUtil.compileCode(codeCmdRun);

            String message = runResult.getMessage();
            String result = runResult.getOutput();
            Long time = runResult.getTime();
            if (time > maxTime) {
                maxTime = time;
            }
            sandBoxVO.setBoxMessage(message);
            //2) 运行错误
            if (!"success".equals(runResult.getMessage())) {
                judgeInfo.setMessage("系统错误");
                judgeInfo.setTime(maxTime);
                sandBoxVO.setJudgeInfo(judgeInfo);
                return sandBoxVO;
            }
            outputValues.add(result);
        }
        //3) 运行成功
        sandBoxVO.setOutput(outputValues);
        judgeInfo.setMessage("判题成功");
        judgeInfo.setTime(maxTime);
        sandBoxVO.setJudgeInfo(judgeInfo);
        return sandBoxVO;
    }
}
